<?php
/**
 * Created by Silent Night.
 * Author: Silent Night
 * email: silentwolf_wp@163.com
 * Date: 2017/9/28
 * Time: 9:19
 */

namespace app\admin\controller;

use think\Controller;
use think\Db;
use think\Session;

class Rentdevice extends Controller
{
    private $_model;
    private $title_field = [
    ];
    public $pagesize = 10;
    public $tyList = array(
    );

    public $allMuiscTypeLists = array();

    public function _initialize()
    {
        $this->_model = new \app\admin\model\NewwindDevice();
        $this->assign('LoginUserInfo', $this->LoginUserInfo);

        //获取当前用户的权限信息
        $this->assign('ruleLists', $this->LoginUserInfo['CurrPower']);
        $this->tyList = getAllNewwindProduct();
        $this->assign('tyList', $this->tyList);

   }

    public function shangData()
    {
        $return = [];
        $id = trim(input("request.id"));//auth
        if (empty($id)) {
            $return = ['err' => 1, 'msg' => '操作失败'];
            return json($return);
        }
        $res = $this->_model->updateData(array('stats' => 0), $id);
        if ($res || $res === 0) {
            $return = ['err' => 0, 'msg' => '操作成功'];
            return json($return);
        } else {
            $return = ['err' => 3, 'msg' => '操作失败'];
            return json($return);
        }
    }

    public function xiaData()
    {
        $return = [];
        $id = trim(input("request.id"));//auth
        if (empty($id)) {
            $return = ['err' => 1, 'msg' => '操作失败'];
            return json($return);
        }
        $res = $this->_model->updateData(array('stats' => 1), $id);

        if ($res || $res === 0) {
            $return = ['err' => 0, 'msg' => '操作成功'];
            return json($return);
        } else {
            $return = ['err' => 3, 'msg' => '操作失败'];
            return json($return);
        }
    }

    /**
     * 列表页
     * @return mixed
     */
    public function index()
    {
        return $this->fetch('index');
    }

    public function lists()
    {
        $ser_key = trim(input("request.ser_key"));//auth
        $ser_val = trim(input("request.ser_val"));//auth
        $ser_device_type = trim(input("request.pid"));//auth


        if ($ser_key && $ser_val) {
            $where[$ser_key] = array('like', '%' . $ser_val . '%');
        }
        if ($ser_device_type > 0) {
            $where['device_type'] = $ser_device_type;
        }
        $model = new \app\admin\model\NewwindDeviceView();
        $lists = $model->lists($where, $this->pagesize);
        $lists['data'] = changeUidToUserinfoForLists($lists['data'], 'uid');
        foreach ($lists['data'] as $key=>$val){
            $lists['data'][$key]['RoomInfo']=[];
            if($val['uid'] && $val['room_id']){
                $RoomInfo = $this->getRoomInfo($val['uid'],$val['room_id']);
                if($RoomInfo){
                    $lists['data'][$key]['RoomInfo']=$RoomInfo;
                }
            }
        }
        $this->assign('lists', $lists);
        $this->assign('request', input("request."));
        return view('lists');
    }

    public function getRoomInfo($uid,$roomid){
        return (new \app\admin\model\NewwindRoom())->getDataForWhere(['uid'=>$uid,'id'=>$roomid]);
    }

    public function getCountForDevice($device_sn){
        if(empty($device_sn)){
            return 0;
        }
        $num = (new \app\admin\model\Dev())->getCount(['devsn'=>$device_sn,'is_rent'=>1]);
        if(empty($num)){
            $num=0;
        }
        return $num;
    }

    public function daoru()
    {
        $sys_opt = trim(input("request.sys_opt")); // auth
        $pid = trim(input("request.pid")); // auth
        // 设置全局信息
        if ($sys_opt) {
            $data = $_REQUEST['lists'];
            if(empty($data)){
                $return = ['err' => 1, 'msg' => '导入数据为空'];
                return json($return);
            }
            $data= json_decode($data,true);
            if(empty($data)){
                $return = ['err' => 1, 'msg' => '导入数据为空'];
                return json($return);
            }

            //获取产品信息
            $productInfo = (new \app\admin\model\NewwindProduct())->getID($pid);
            if(empty($productInfo)){
                $return = ['err' => 1, 'msg' => '产品不存在'];
                return json($return);
            }
            $insertDataArr=[];
            $deviceJson=[];
            $devicenickname=$productInfo['name'];
            foreach ($data as $key=>$val){
                if($key==0){
                    continue;
                }
                $insertData = array(
                    'devicename'=>$val['DeviceName'],
                    'nickname'=>$val['Nickname'],
                    'product_id'=>$productInfo['id'],
                    'devicenickname'=>$devicenickname,
                    'ctime'=>date("Y-m-d H:i:s"),
                );
                $insertDataArr[]=$insertData;
                $model = new \app\admin\model\NewwindDevice();
                $flag = $model->insert($insertData,"IGNORE");
                if($flag){
                    $deviceJson[]=$val;
                }
            }
//            if($insertDataArr) {
//                $model = new \app\admin\model\NewwindDevice();
//                $model->addAll($insertDataArr);
//            }
            if($deviceJson) {
                $url = "http://8.131.73.193:90/demo/device_reg.php";
                $param = array(
                    'productKey' => $productInfo['productkey'],
                    'deviceJson' => json_encode($deviceJson,true),
                );
               $res =  get_url($url, $param);
            }
            $return = ['err' => 0, 'msg' => '导入成功'];
            return json($return);
        }

        $title = "导入";
        $this->assign('title', $title);
        return view('daoru');
    }

    public function getRendPosionInfo($name){
        $model = new \app\admin\model\RentPosition();
        return  $model->getDataForWhere(['name'=>$name]);
    }
    public function insertPosion($name){
        $model = new \app\admin\model\RentPosition();
        return  $model->add(['name'=>$name]);
    }

    public function parseexcel()
    {
        $file = $_REQUEST['file'];
        $pid = $_REQUEST['pid'];
        $ty = $_REQUEST['ty']; // 1单选题模板 2互选题模板 3填空题模板
        $path = ROOT_PATH . "/public" . $file;
        $data = $this-> actionImport($path);
        $return = [
            'err' => 0,
            'msg' => '解析成功',
            'data' => $data
        ];

        return json($return);
    }


    public function actionImport($fileTmpName)
    {
        $Collection = [];
//打开要读的文件
        $handle = fopen($fileTmpName, 'r');
//解析csv文件
        while (!feof($handle)) {
//fgets方法按行读
            $result = fgets($handle);
            $result = mb_convert_encoding($result, "UTF-8", "GBK");
            $result = trim($result);
//判断读到的每一行是否有值
            if (!empty($result)) {
                $arrResult = explode(",", $result);
                $tempData =array(
                    'DeviceName'=> $arrResult[0],
                    'Nickname'=> $arrResult[1],
                );
                $Collection[]=$tempData;
            }
        }
//关闭文件流
        fclose($handle);
        return $Collection;
    }

    /**
     * 删除
     * 支持批量删除和单条删除
     * @return mixed
     */
    public function delData()
    {
        $return = [];
        $id = trim(input("request.id"));//auth
        if (empty($id)) {
            $return = ['err' => 1, 'msg' => '操作失败'];
            return json($return);
        }
        $res = $this->_model->delData(array('id' => $id));
        if ($res) {
            $return = ['err' => 0, 'msg' => '操作成功'];
            return json($return);
        } else {
            $return = ['err' => 3, 'msg' => '操作失败'];
            return json($return);
        }

    }

    public function addData()
    {
        $sys_opt = trim(input("request.sys_opt"));//auth
        $this->getRendPositonLists();
        if ($sys_opt) {
            $data1 = $_REQUEST['data'];
            $data2 = array(
                'ctime' => time(),
            );
            $data = array_merge($data1, $data2);
            $res = $this->_model->add($data);
            if ($res) {
                $return = ['err' => 0, 'msg' => '操作成功'];
                return json($return);
            } else {
                $return = ['err' => 3, 'msg' => '操作失败'];
                return json($return);
            }
        }
        $title = "添加";
        $this->assign('title', $title);
        return view('addData');
    }

    public function infoData()
    {

        $id = trim(input("request.id"));//auth

        $info = $this->_model->getDataForWhere(array('id' => $id));
        $this->getRendPositonLists();

        $info['UserInfo'] = array();
        if ($info['uid']) {
            $info['UserInfo'] = getUserInfoForID($info['uid']);
        }

        $this->assign('info', $info);
        $title = "详情";
        $this->assign('title', $title);
        $this->assign('id', $id);
        return view('infoData');

    }


    public function editData()
    {

        $id = trim(input("request.id"));//auth
        $sys_opt = trim(input("request.sys_opt"));//auth
        //查询用户
        $info = $this->_model->getDataForWhere(array('id' => $id));
        $this->getRendPositonLists();

        if ($sys_opt) {
            $data1 = $_REQUEST['data'];
            $w = array(
                'id' => $id
            );
            $data2 = array(
            );
            $data = array_merge($data1, $data2);
            $res = $this->_model->updateDataForWhere($data, $w);

            if ($res || ($res === 0)) {

                $return = ['err' => 0, 'msg' => '操作成功'];
                return json($return);
            } else {
                $return = ['err' => 3, 'msg' => '操作失败'];
                return json($return);
            }
        }

        $this->assign('info', $info);
        //设置全局信息
        $title = "编辑";
        $this->assign('title', $title);
        $this->assign('id', $id);
        return view('editData');

    }
}